<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <title>Flask + Dict CRUD</title>
  <style>
    body{font-family:Arial,Helvetica,sans-serif;margin:40px}
    table{border-collapse:collapse;width:100%}
    th,td{border:1px solid #ccc;padding:6px 10px;text-align:left}
    input[type=text],input[type=number]{width:90%}
  </style>
</head>
<body>
  <h2>用户管理（Flask + dict 版）</h2>

  <h3>新增 / 修改</h3>
  <form id="userForm">
    <input type="hidden" id="userId"/><br>
    <label>姓名：<input type="text" id="name" required/></label><br>
    <label>年龄：<input type="number" id="age" min="0"/></label><br>
    <label>城市：<input type="text" id="city"/></label><br>
    <button type="submit">保存</button>
    <button type="button" onclick="resetForm()">重置</button><br>
  </form>

  <h3>用户列表</h3>
  <input type="text" id="q" placeholder="按姓名模糊查询"/>
  <button onclick="loadList()">搜索</button>
  <table>
    <thead><tr><th>ID</th><th>姓名</th><th>年龄</th><th>城市</th><th>操作</th></tr></thead>
    <tbody id="list"></tbody>
  </table>

<script>
const API = '/api/users';
function resetForm(){
  document.getElementById('userForm').reset();
  document.getElementById('userId').value='';
}
async function loadList(){
  const q=document.getElementById('q').value.trim();
  const res=await fetch(API+(q?`?name=${q}`:''));
  const data=await res.json();
  const html=data.map(u=>`
    <tr>
      <td>${u.id}</td><td>${u.name}</td><td>${u.age}</td><td>${u.city}</td>
      <td>
        <button onclick="editUser(${u.id},'${u.name}',${u.age},'${u.city}')">改</button>
        <button onclick="delUser(${u.id})">删</button>
      </tr>`).join('');
  document.getElementById('list').innerHTML=html;
}
function editUser(id,name,age,city){
  document.getElementById('userId').value=id;
  document.getElementById('name').value=name;
  document.getElementById('age').value=age;
  document.getElementById('city').value=city;
}
async function delUser(id){
  await fetch(`${API}/${id}`,{method:'DELETE'});
  loadList();
}
document.getElementById('userForm').addEventListener('submit',async e=>{
  e.preventDefault();
  const id=document.getElementById('userId').value;
  const payload={
    name:document.getElementById('name').value.trim(),
    age:Number(document.getElementById('age').value),
    city:document.getElementById('city').value.trim()
  };
  const url=id?`${API}/${id}`:API;
  const method=id?'PUT':'POST';
  await fetch(url,{method,headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
  resetForm();
  loadList();
});
// 初始化
loadList();
</script>
</body>
</html>